package com.chengqs.dfs.namenode.server;

import com.chengqs.dfs.namenode.rpc.service.NameNodeServiceGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * <B>主类名称：</B>HelloServer<BR>
 * <B>概要说明：</B>enter<BR>
 *
 * @author: chengqs
 * @create: 2025-03-30 17:46:06
 **/
@Slf4j
public class NameNodeRpcServer {

    private static final int DEFAULT_PORT = 50070;

    private Server server = null;

    /**
     * 负责管理元数据的核心组件
     */
    private FSNameSystem nameSystem;
    /**
     * 负责管理集群中所有的datanode的组件
     */
    private DataNodeManager datanodeManager;

    public NameNodeRpcServer(FSNameSystem nameSystem, DataNodeManager datanodeManager) {
        this.nameSystem = nameSystem;
        this.datanodeManager = datanodeManager;
    }

    public void start() throws IOException {
        // 启动一个rpc server，监听指定的端口
        // 同时绑定好了自己开发的接口
        server = ServerBuilder
                .forPort(DEFAULT_PORT)
                .addService(NameNodeServiceGrpc.bindService(new NameNodeServiceImpl(nameSystem, datanodeManager)))
                .build()
                .start();

        log.info("NameNodeRpcServer启动，监听端口号：{}", DEFAULT_PORT);

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                NameNodeRpcServer.this.stop();
            }
        });
    }

    public void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    public void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
